package com.dongdongshop.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import com.dongdongshop.vo.SpecVO;
import com.dongdongshop.vo.TemplateVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.*;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Controller
@RequestMapping("goods")
public class TbGoodsController {

    private Logger logger = LoggerFactory.getLogger(TbGoodsController.class);
    @DubboReference
    private TbGoodsService goodsService;
    @DubboReference
    private TbItemCatService catService;
    @DubboReference
    private TbTypeTemplateService templateService;
    @DubboReference
    private TbSpecificationService specService;

    @RequestMapping("show")
    public String show() {
        return "admin/goods_edit";
    }

    @RequestMapping("select")
    @ResponseBody
    public Result select(Long id) {
        try {
            List<TbItemCat> catList = catService.listCat(id);
            return Result.OK().setData(catList);
        } catch (Exception e) {
            logger.info("批量删除方法异常 {}", e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("selectId")
    @ResponseBody
    public Result selectId(Long id) {
        try {
            TbItemCat cat = catService.selectCatById(id);
            return Result.OK().setData(cat);
        } catch (Exception e) {
            logger.info("批量删除方法异常 {}", e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("selectBrand")
    @ResponseBody
    public Result selectBrand(Long id) {
        try {
            TbTypeTemplate template = templateService.selectTemplate(id);
            return Result.OK().setData(template);
        } catch (Exception e) {
            logger.info("批量删除方法异常 {}", e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("selectTemplateVo")
    @ResponseBody
    public Result selectTemplateVo(Long id) {
        try {
            TbTypeTemplate template = templateService.selectTemplate(id);
            String specIds = template.getSpecIds();
            List<SpecVO> specVOS = JSONUtil.toList(specIds, SpecVO.class);
            for (SpecVO specVO : specVOS) {
                SpecVO specVO1 = specService.selectSpecAndOptionById(specVO.getId());
                specVO.setOptionList(specVO1.getOptionList());
            }
            TemplateVo templateVo = new TemplateVo();
            BeanUtil.copyProperties(template,templateVo);
            templateVo.setSpecVOList(specVOS);
            return Result.OK().setData(templateVo);
        } catch (Exception e) {
            logger.info("批量删除方法异常 {}", e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("addGoods")
    @ResponseBody
    public Result addGoods(TbGoods good, TbGoodsDesc tgd,String itemString) {
        try {
            List<TbItem> tbItems = JSONUtil.toList(itemString, TbItem.class);
            TbSeller seller = (TbSeller) SecurityUtils.getSubject().getPrincipal();
            for (TbItem tbItem : tbItems) {
                tbItem.setSeller(seller.getNickName());
                tbItem.setStatus("1");
                tbItem.setSellerId(seller.getSellerId());
                //通过LocalDateTime.now()获取当前的时间，具体到年月日时分秒
                LocalDateTime localDateTime = LocalDateTime.now();
//Zoneld用于标识在Instant和LocalDateTime之间的转换规则，同时也是时区ID
//通过ZoneId的systemDefault获取系统默认时区
                ZoneId zoneId = ZoneId.systemDefault();
//LocalDateTime只是能显示本地日期和时间，没有时区
//ZoneIdDateTime要标识一个带时区的日期和时间
//ZonedDateTime相当于LocalDateTime+ZoneId
//通过LocalDateTime的atZone(new ZoneID)把LocalDateTime转换为ZoneDateTime
                ZonedDateTime zonedDateTime =localDateTime.atZone(zoneId);
//Instant类用于在应用程序中记录事件的时间戳
//也即是把时间转化为一瞬间
//ZonedDateTime.toInstant是用于把ZonedDateTime转为Instant类型
                Instant instant = zonedDateTime.toInstant();
//使用Date.from(new instant)方法,改为Date类型,该日期表示时间轴上与传递的瞬间相同的点。
                Date date = Date.from(instant);
                tbItem.setCreateTime(date);
                tbItem.setUpdateTime(date);
            }
            good.setSellerId(seller.getSellerId());
            goodsService.addGoodsAndGoodsDesc(good, tgd,tbItems);
            return Result.OK();
        } catch (Exception e) {
            logger.info("商品增加方法异常 {}", e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }

    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("myFile") MultipartFile myFile){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tAzLoxGg1pwiTALqmNQ";
        String accessKeySecret = "QnvvcqC7AA0CQ4KXyCnT5gePimSj9v";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ssl-2204";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "image/" + myFile.getOriginalFilename();
        //https://ssl-2204.oss-cn-beijing.aliyuncs.com/image/collection_pic.jpg
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http + endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObject请求。
            InputStream inputStream = myFile.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            return Result.OK().setData(imageUrl);
        } catch (Exception oe) {
            oe.printStackTrace();
            return Result.ERROR();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}